import React, { Component, Fragment } from 'react'
import TodoItem from './todo-item'
import './style.css'
import axios from 'axios'

export default class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: '',
      list: []
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    this.handleItemDelete = this.handleItemDelete.bind(this)
  }
  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input 
          className="input"
          id="insertArea"
          ref={(input) => {this.input = input}}
          value={this.state.inputValue} 
          onChange={this.handleChange} />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul ref={(ul) => {this.ul = ul}}>
          { this.getTodoItem() }
        </ul>
      </Fragment>
    )
  }
  componentDidMount() {
    axios.get('/api/todolist').then(res => {
      console.log('succ')
    }).catch(err => {
      console.log('error')
    })
  }
  getTodoItem() {
    return this.state.list.map((item, index) => {
      return (
        <TodoItem 
          content={item} 
          index={index} 
          key={index} 
          deleteItem={this.handleItemDelete}
          ></TodoItem>
      )
    })
  }
  handleChange(e) {
    const value = e.target.value
    this.setState(() => ({
      inputValue: value
    }))
  }
  handleBtnClick(e) {
    // 以为setState的执行时异步操作，故要在这个方法的回调执行dom查询操作
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ''
    }), () => {
      // console.log(this.ul.querySelectorAll('li').length)
    })
    
  }
  handleItemDelete(index) {
    this.setState((prevState) => {
      const list = [...prevState.list]
      list.splice(index, 1)
      return { list }
    })

  }
}
